package org.stephen.recommend.model;

import com.baomidou.mybatisplus.extension.activerecord.Model;
import org.stephen.recommend.util.CommonUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: SimilarityUser
 * Description:
 * Date: 2020/12/16 14:24
 *
 * @author stephen.qiu
 */
public class SimilarityUsers extends Model<SimilarityUsers> {
    private static final long serialVersionUID = 1L;

    private HashMap<String, LocalDateTime> similarityUserTimeMap;

    public HashMap<String, LocalDateTime> getSimilarityUserTimeMap() {
        return similarityUserTimeMap;
    }

    public SimilarityUsers() {
        setSimilarityUserTimeMap(new HashMap<>(CommonUtils.initHashMapSize(0)));
    }

    public void setSimilarityUserTimeMap(HashMap<String, LocalDateTime> similarityUserTimeMap) {
        this.similarityUserTimeMap = similarityUserTimeMap;
    }

    public List<String> getSimilarityUsersList() {
        List<Map.Entry<String, LocalDateTime>> list = new ArrayList<>(similarityUserTimeMap.entrySet());
        return list.stream().map(c -> c.getKey()).collect(Collectors.toList());
    }

    /**
     * 移除previousDays内未重新建立连接的相似用户
     *
     * @param previousDays
     */
    public void updateSimilarityUsers(int previousDays) {
        Iterator<Map.Entry<String, LocalDateTime>> iterator = similarityUserTimeMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, LocalDateTime> entry = iterator.next();
            if (entry.getValue().isBefore(LocalDateTime.now().plusDays(0 - previousDays))) {
                iterator.remove();
            }
        }
    }

    /**
     * 更新相似用户，返回新添加数量
     *
     * @param userIds
     * @return
     */
    public int updateSimilarityUsers(List<String> userIds) {
        int add = 0;
        for (String similarityUser : userIds) {
            if (!similarityUserTimeMap.containsKey(similarityUser)) {
                add++;
            }
            similarityUserTimeMap.put(similarityUser, LocalDateTime.now());
        }
        return add;
    }
}
